#include<stdio.h>
#include<stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include<stdbool.h>
#include<pthread.h>
#include<string.h>
#include<linux/fb.h>
void *routine(void *arg)
{
	pthread_detach(pthread_self());
	int *a=(int*) arg;
	printf("xc:%d\n",*a);
	system("killall madplay");
	switch(((*a-1)/66))
	{
		case 0: system("./madplay d1.mp3");break;
		case 1: system("./madplay d2.mp3");break;
		case 2: system("./madplay d3.mp3");break;
		case 3: system("./madplay d4.mp3");break;
		case 4: system("./madplay d5.mp3");break;
		case 5: system("./madplay d6.mp3");break;
		case 6: system("./madplay d7.mp3");break;
		case 7: system("./madplay d8.mp3");break;
		case 8: system("./madplay d9.mp3");break;
		case 9: system("./madplay d10.mp3");break;
		case 10:system("./madplay d11.mp3");break;
		case 11:system("./madplay d12.mp3");break;
		default: break;
	}

}



int main(void)
{

	struct fb_var_screeninfo vinfo;
	char *FB = init_lcd(&vinfo);

	/*int frm_size  = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel/8;
	char *reserve = calloc(1, frm_size);
	memcpy(reserve, FB, frm_size);*/

	bmp_show("background.bmp", FB, &vinfo, 0, 0);
	bmp_show("bar.bmp", FB, &vinfo, 0, 0);
	int i=0;

	for(i=0; i<12; i++)
	{
		bmp_show("key_off.bmp", FB, &vinfo,1+i*66, 48);
	}
	int ts = open("/dev/input/event0", O_RDONLY);
	if(ts == -1)
	{
		perror("open /dev/input/event0 failed");
		exit(0);
	}
	int x,y;
	int leave=-67,b=0;
	int xc;

	pthread_attr_t attr;
	pthread_attr_init(&attr);

	// 将分离属性PTHREAD_CREATE_DETACHED加入到这个属性变量中
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	while(1)
	{
		bool do1 = wait4touch(ts, &x, &y);
		pthread_t tid, t1, t2;

		if(y>47 && y<328 && x<793)
		{
		
			if((leave/66 == x/66) && do1 )
			{
				
				continue;
			}
				printf("leaved:%d\n",1+((x-1)/66)*66);
			if(do1)
			{
				xc =x;
				bmp_show("key_on.bmp", FB, &vinfo,1+((x-1)/66)*66, 48);
				pthread_create(&tid, &attr, routine, (void *) &xc);
				

			}
			if(!do1)
			{
				bmp_show("key_off.bmp", FB, &vinfo,1+((x-1)/66)*66, 48);
				leave=-67;
				continue;
			}

			if(leave != -67 && do1 == true)
			{
				bmp_show("key_off.bmp", FB, &vinfo,1+((leave-1)/66)*66, 48);
			}

			
			
			leave = x;
		}
		
		if(y<47 || y>328)
		{
			bmp_show("key_off.bmp", FB, &vinfo,1+((x-1)/66)*66, 48);
			leave=-67;
		}
	}
	return 0;
}
